package com.joinpay.config;


import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * MyBatis配置
 *
 */
@MapperScan(basePackages="com.joinpay.dao")    //指定mybatis实现的dao接口(可以实现接口开发)
@Configuration
@ConfigurationProperties(prefix = "config")
public class MyBatisConfig {
	
	private ComboPooledDataSource dataSource;
	
	private SqlSessionFactoryBean sqlSessionFactoryBean;
	
	private SqlSessionDaoSupport sqlSessionDaoSupport;
	
	
	/**
	 * 创建c3p0数据源
	 * @return
	 */
	@Bean
//	@ConfigurationProperties(prefix = "c3p0.dataSource")   //指定该数据源在properties中使用的前缀
	public ComboPooledDataSource getDataSource(){
		if(dataSource == null){
			dataSource = new ComboPooledDataSource();
		}
		return dataSource;
	}
	
	/**
	 * 创建SqlSessionFactory
	 * @throws Exception 
	 */
	@Bean
	@ConfigurationProperties(prefix = "mybatis")
	public SqlSessionFactory getSqlSessionFactory() throws Exception{
		if(sqlSessionFactoryBean == null){
			sqlSessionFactoryBean = new SqlSessionFactoryBean();
		}
		sqlSessionFactoryBean.setDataSource(getDataSource());
//		sqlSessionFactoryBean.setTypeAliasesPackage("com.lm.dao");
//		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();  
//        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis.xml/*.xml"));//指定mapper文件所在目录
		return sqlSessionFactoryBean.getObject();
	}

	
	public SqlSessionDaoSupport getSqlSessionDaoSupport() throws Exception {
		sqlSessionDaoSupport.setSqlSessionFactory(getSqlSessionFactory());
		return sqlSessionDaoSupport;
	}

	public void setSqlSessionDaoSupport(SqlSessionDaoSupport sqlSessionDaoSupport) {
		this.sqlSessionDaoSupport = sqlSessionDaoSupport;
	}

	public SqlSessionFactoryBean getSqlSessionFactoryBean() {
		return sqlSessionFactoryBean;
	}

	public void setSqlSessionFactoryBean(SqlSessionFactoryBean sqlSessionFactoryBean) {
		this.sqlSessionFactoryBean = sqlSessionFactoryBean;
	}

	public void setDataSource(ComboPooledDataSource dataSource) {
		this.dataSource = dataSource;
	}
	
	
}
